<template>
  <view class="order-confirm-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">确认订单</text>
    </view>

    <!-- 收货地址 -->
    <view class="address-section" @tap="selectAddress">
      <view class="section-header">
        <text class="section-title">收货地址</text>
        <text class="change-btn">更换</text>
      </view>
      
      <view class="address-content" v-if="selectedAddress">
        <view class="address-info">
          <text class="receiver-name">{{ selectedAddress.receiverName }}</text>
          <text class="receiver-phone">{{ selectedAddress.receiverPhone }}</text>
        </view>
        <text class="address-detail">{{ selectedAddress.provinceName + selectedAddress.cityName + selectedAddress.districtName + (selectedAddress.street ? selectedAddress.street : '') + selectedAddress.detailAddress }}</text>
      </view>
      
      <view class="no-address" v-else>
        <text class="no-address-text">请选择收货地址</text>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="product-section">
      <view class="section-header">
        <text class="section-title">商品信息</text>
      </view>
      
      <view class="product-item" v-if="orderData">
        <image class="product-image" :src="orderData.image" mode="aspectFill"></image>
        <view class="product-details">
          <text class="product-name">{{ orderData.productName}}</text>
          <view class="product-price-qty">
            <text class="product-price">¥{{ orderData.salePrice }}</text>
            <text class="product-qty">x{{ orderData.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 配送方式 -->
    <view class="delivery-section">
      <view class="section-header">
        <text class="section-title">配送方式</text>
      </view>
      
      <view class="delivery-options">
        <view class="delivery-item" :class="{ selected: selectedDelivery === 'zhongtong' }" @tap="selectDelivery('zhongtong')">
          <view class="delivery-info">
            <text class="delivery-name">中通快递</text>
            <text class="delivery-desc">预计2-3天送达</text>
          </view>
          <view class="radio" :class="{ checked: selectedDelivery === 'zhongtong' }">
            <text class="radio-icon" v-if="selectedDelivery === 'zhongtong'">✓</text>
          </view>
        </view>
        
        <view class="delivery-item" :class="{ selected: selectedDelivery === 'yuantong' }" @tap="selectDelivery('yuantong')">
          <view class="delivery-info">
            <text class="delivery-name">圆通快递</text>
            <text class="delivery-desc">预计2-3天送达</text>
          </view>
          <view class="radio" :class="{ checked: selectedDelivery === 'yuantong' }">
            <text class="radio-icon" v-if="selectedDelivery === 'yuantong'">✓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单备注 -->
    <view class="remark-section">
      <view class="section-header">
        <text class="section-title">订单备注</text>
      </view>
      
      <textarea 
        class="remark-input" 
        v-model="orderRemark" 
        placeholder="选填，请输入订单备注信息"
        maxlength="100"
        :show-count="true"
      ></textarea>
    </view>

    <!-- 价格明细 -->
    <view class="price-section" v-if="orderData">
      <view class="price-item">
        <text class="price-label">商品金额</text>
        <text class="price-value">¥{{ productTotal }}</text>
      </view>
      <view class="price-item">
        <text class="price-label">配送费</text>
        <text class="price-value">¥{{ deliveryFee }}</text>
      </view>
      <view class="price-item total-price">
        <text class="price-label">实付款</text>
        <text class="price-value total">¥{{ totalAmount }}</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="price-summary">
        <text class="total-label">合计：</text>
        <text class="total-amount">¥{{ totalAmount }}</text>
      </view>
      <view class="submit-btn" @tap="submitOrder">
        <text class="btn-text">提交订单</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import api from "@/utils/api"
import storageUtil from '@/utils/storage'
// 响应式数据
const productInfo = ref({})
const orderData = ref()
const selectedAddress = ref(null)
const deliveryFee = ref(0)
const orderRemark = ref('')
const loading = ref(false)
const selectedDelivery = ref('zhongtong') // 默认选择中通快递

// 计算属性
const productTotal = computed(() => {
  const price = orderData.value.salePrice
  const quantity = orderData.value.quantity
  return (price * quantity).toFixed(2)
})

const totalAmount = computed(() => {
  return (parseFloat(productTotal.value) + deliveryFee.value).toFixed(2)
})

// 加载默认地址
const loadDefaultAddress = async () => {
  try {
    if (storageUtil.address.getSelectedAddress()) {
      console.log(storageUtil.address.getSelectedAddress())
      selectedAddress.value = storageUtil.address.getSelectedAddress()
      return
    }
    // 获取openId
    const openId = uni.getStorageSync('openid')
    if (!openId) {
      uni.showToast({
        title: '用户信息获取失败，请重新登录',
        icon: 'none'
      })
      loading.value = false
      return
    }
    const defaultAddressResp = await api.address.getDefaultAddress(openId)
    if (defaultAddressResp && defaultAddressResp.code === 0) {
      selectedAddress.value = defaultAddressResp.data
    }
  } catch (error) {
    console.error('加载默认地址失败:', error)
  }
}

// 选择地址
const selectAddress = () => {
  uni.navigateTo({
    url: selectedAddress.value ? `/pages/address/address?mode=select&selectedId=${selectedAddress.value.id}` : '/pages/address/address?mode=select',
  })
}

// 选择配送方式
const selectDelivery = (deliveryType) => {
  selectedDelivery.value = deliveryType
}

// 提交订单
const submitOrder = async () => {
  if (!selectedAddress.value) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none'
    })
    return
  }
  
  loading.value = true
  
  try {
    // 创建订单数据
    const result = {
      productId: orderData.value.id,
      productName: orderData.value.productName,
      productPrice: orderData.value.salePrice,
      quantity: orderData.value.quantity,
      deliveryFee: deliveryFee.value,
      totalAmount: totalAmount.value,
      remark: orderRemark.value,
      address: {
        name: selectedAddress.value.receiverName,
        phone: selectedAddress.value.receiverPhone,
        fullAddress: selectedAddress.value.provinceName + selectedAddress.value.cityName + selectedAddress.value.districtName + (selectedAddress.value.street ? selectedAddress.value.street : '') + selectedAddress.value.detailAddress
      },
      status: 'pending', // 待支付
      createTime: new Date().toISOString()
    }
    
    // 这里应该调用后端API创建订单
    // const res = await api.createOrder(orderData)
    // const orderId = res.data.orderId
    
    // 临时生成订单ID
    const orderId = 'ORDER' + Date.now()
    orderData.id = orderId
    
    // 临时保存到本地存储
    let orderList = uni.getStorageSync('orderList') || []
    orderList.unshift(orderData)
    uni.setStorageSync('orderList', orderList)
    
    // 跳转到支付页面
    uni.redirectTo({
      url: `/pages/payment/payment?orderId=${orderId}&amount=${totalAmount.value}`
    })
    
  } catch (error) {
    console.error('提交订单失败:', error)
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 监听地址选择结果
uni.$on('addressSelected', (address) => {
  selectedAddress.value = address
})

// 生命周期
onLoad((options) => {
  console.log('页面参数:', options)
  
  // 从页面参数获取商品信息
  if (options.data) {
    try {
      orderData.value = JSON.parse(decodeURIComponent(options.data))
      console.log('购买参数', orderData.value)
    } catch (error) {
      console.error('解析商品数据失败:', error)
      uni.showToast({
        title: '商品信息错误',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
  } else {
    // 如果没有传递商品数据，设置默认值或从其他地方获取
    console.log('未获取到商品数据，检查页面跳转参数')
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
  
  // 加载默认地址
  loadDefaultAddress()
})

onShow(() => {
  if (storageUtil.address.getSelectedAddress()) {
    selectedAddress.value = storageUtil.address.getSelectedAddress()
  }
})

// 页面卸载时移除监听
onMounted(() => {
  uni.$off('addressSelected')
})
</script>

<style scoped>
.order-confirm-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

/* 页面标题 */
.page-header {
  background: white;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 通用区块样式 */
.address-section,
.product-section,
.delivery-section,
.remark-section,
.price-section {
  background: white;
  margin: 16px;
  border-radius: 12px;
  overflow: hidden;
}

.section-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.change-btn {
  font-size: 14px;
  color: #FFB800;
}

/* 收货地址 */
.address-content {
  padding: 16px 20px;
}

.address-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.receiver-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.receiver-phone {
  font-size: 14px;
  color: #666;
}

.address-detail {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.no-address {
  padding: 40px 20px;
  text-align: center;
}

.no-address-text {
  font-size: 14px;
  color: #999;
}

/* 商品信息 */
.product-item {
  padding: 16px 20px;
  display: flex;
  gap: 12px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  flex-shrink: 0;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  line-height: 1.3;
}

.product-spec {
  font-size: 12px;
  color: #999;
}

.product-price-qty {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.product-price {
  font-size: 18px;
  color: #FF4444;
  font-weight: bold;
}

.product-qty {
  font-size: 14px;
  color: #666;
}

/* 配送方式 */
.delivery-options {
  padding: 0;
}

.delivery-item {
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.delivery-item:last-child {
  border-bottom: none;
}

.delivery-item.selected {
  background: #FFF8E1;
  border-color: #FFB800;
}

.delivery-info {
  flex: 1;
}

.delivery-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
  margin-right: 4rpx;
}

.delivery-desc {
  font-size: 12px;
  color: #999;
}

.radio {
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.radio.checked {
  border-color: #FFB800;
  background: #FFB800;
}

.radio-icon {
  font-size: 12px;
  color: white;
  font-weight: bold;
}

/* 订单备注 */
.remark-input {
  padding: 16px 20px;
  font-size: 14px;
  color: #333;
  min-height: 80px;
  width: 100%;
  box-sizing: border-box;
}

/* 价格明细 */
.price-item {
  padding: 12px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.price-item:last-child {
  border-bottom: none;
}

.price-item.total-price {
  padding: 16px 20px;
  background: #fafafa;
}

.price-label {
  font-size: 14px;
  color: #666;
}

.price-value {
  font-size: 14px;
  color: #333;
}

.price-value.total {
  font-size: 18px;
  color: #FF4444;
  font-weight: bold;
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.price-summary {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 4px;
}

.total-label {
  font-size: 14px;
  color: #666;
}

.total-amount {
  font-size: 20px;
  color: #FF4444;
  font-weight: bold;
}

.submit-btn {
  background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%);
  border-radius: 24px;
  padding: 12px 32px;
  box-shadow: 0 4px 12px rgba(255, 184, 0, 0.3);
  transition: all 0.3s ease;
}

.submit-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(255, 184, 0, 0.3);
}

.btn-text {
  font-size: 16px;
  color: white;
  font-weight: bold;
}
</style>